package cn.ztydata.teachingsystem.heaven.service;

import cn.ztydata.teachingsystem.common.Page;
import cn.ztydata.teachingsystem.exception.ServiceException;
import cn.ztydata.teachingsystem.heaven.common.WebContext;
import cn.ztydata.teachingsystem.heaven.cons.Roles;
import cn.ztydata.teachingsystem.heaven.dao.DailyCommentDao;
import cn.ztydata.teachingsystem.heaven.dao.DailyDao;
import cn.ztydata.teachingsystem.heaven.dao.SpecialtyDao;
import cn.ztydata.teachingsystem.heaven.dao.redis.DailyComCountDao;
import cn.ztydata.teachingsystem.heaven.entity.Daily;
import cn.ztydata.teachingsystem.heaven.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * 教学日志业务类
 *
 * @author lyj
 * @since 2015/5/6
 */
@Service
public class DailysService extends BaseService {
    @Autowired
    private DailyDao dailyDao;
    @Autowired
    private DailyComCountDao dailyComCountDao;
    @Autowired
    private WebContext webContext;
    @Autowired
    private SpecialtyDao specialtyDao;
    @Autowired
    private SpecialtyGroupService specialtyGroupService;
    @Autowired
    private DailyCommentDao dailyCommentDao;

    //<editor-fold desc="验证">
    /**
     * 验证用户角色
     *
     * @author lyj
     * @since 2015-5-7
     */
    public void checkRole() {
        if (webContext.getRole() != Roles.SPEC_LEADER && webContext.getRole() != Roles.TEACHER) {
            log.debug("登录用户没有权限使用该接口webContext.getRole() != Roles.SPEC_LEADER && webContext.getRole() != Roles.TEACHER");

            log.warn("登录用户没有权限使用该接口！登录用户角色->{}", webContext.getRole());
            throw new ServiceException("权限错误！");
        }
    }


    /**
     * 编辑时的创建人验证
     *
     * @param id 教学日志
     * @author lyj
     * @since 2015-5-11
     */
    public void checkCreator(final long id) {

        Boolean check = false;

        //获取教学日志信息，判断教学日志是否已删除
        Daily daily = dailyDao.getDetailById(id);
        if (daily == null) {
            log.debug("获取教学日志明细失败daily == null");
            log.warn("获取教学日志明细失败！");
            throw new ServiceException("教学日志已经被删除！");
        }

        //判断教学日志的创建人
        if (webContext.getUserId().intValue() == daily.getCreatorId().intValue()) {
            log.debug("判断教学日志的创建人webContext.getRole().intValue() == daily.getCreatorId().intValue()");
            check = true;
        }

        if (!check) {
            log.debug("!check");

            log.warn("登录用户没有权限使用该接口");
            throw new ServiceException("权限错误！");
        }

    }


    //</editor-fold>


    //<editor-fold desc="新增">
    /**
     * 新增教学日志
     * @param daily
     * @author lyj
     * @since 2015-5-6
     */
    public void addDaily(final Daily daily) {
        //验证角色
        checkRole();

        if (dailyDao.addDaily(daily) != 1) {
            log.debug("新增教学日志失败dailyDao.addDaily(daily) != 1");
            log.warn("新增教学日志失败!");

            throw new ServiceException("新增教学日志失败！");
        }
    }
    //</editor-fold>


    //<editor-fold desc="删除">
    /**
     * 删除日志
     *
     * @param id 日志ID
     * @return int
     * @author lyj
     * @since 2015-5-6
     */
    public void deleteById(final long id) {
        //验证角色
        checkRole();

        //获取教学日志信息，判断教学日志是否已删除
        Daily daily = dailyDao.getDetailById(id);
        if (daily == null) {
            log.debug("获取教学日志信息daily == null");

            log.warn("获取教学日志明细失败！");
            throw new ServiceException("教学日志已经被删除！");
        }

        //判断教学日志的创建人
        if (webContext.getUserId().intValue() != daily.getCreatorId().intValue()) {

            log.debug("判断教学日志的创建人webContext.getRole().intValue() != daily.getCreatorId().intValue()");

            //判断登录人是否为该专业的负责人
            if (specialtyDao.checkByLeader(daily.getGroupId(), webContext.getUserId()) != 1) {
                log.debug("判断登录人是否为该专业的负责人specialtyDao.checkByLeader(daily.getGroupId(), webContext.getUserId()) != 1");

                throw new ServiceException("权限错误！");
            }
        }

        if (dailyDao.deleteById(id) != 1) {
            log.debug("dailyDao.deleteById(id) != 1");

            log.warn("删除教学日志失败：id->{}", id);

            throw new ServiceException("删除教学日志失败！");
        }

        //删除评论
        dailyCommentDao.deleteByDailyId(id);
    }
    //</editor-fold>


    //<editor-fold desc="编辑">
    /**
     * 编辑日志
     *
     * @param daily
     * @return void
     * @author lyj
     * @since 2015-5-6
     */
    public void updateDaily(final Daily daily) {
        //验证角色
        checkRole();
        //验证并发（是否已经被删除）
        checkCreator(daily.getId());

        if (dailyDao.updateDaily(daily) != 1) {
            log.debug("编辑教学日志失败dailyDao.updateDaily(daily) != 1");
            log.warn("编辑教学日志失败：id->{}", daily.getId());

            throw new ServiceException("编教学日志失败！");
        }
    }


    /**
     * 是否公开
     *
     * @param id 日志ID
     * @param open 是否公开
     * @return void
     * @author lyj
     * @since 2015-5-6
     */
    public void updateOpenById(final long id,final int open) {
        //验证角色
        checkRole();

        //验证并发（日志被删除没有）
        checkCreator(id);

        if (dailyDao.updateOpenById(id, open) != 1) {
            log.debug("编辑教学日志失败dailyDao.updateOpenById(id, open) != 1");
            log.warn("编辑教学日志失败：id->{},open->{}", id, open);

            throw new ServiceException("编教学日志失败！");
        }
    }
    //</editor-fold>


    //<editor-fold desc="查询">

    /**
     * 教学日志列表
     *
     * @param groupId  群组ID
     * @param pageNum  当前页码
     * @param pageSize 每页条数
     * @param tag      标记 0全部 1我的
     * @return Page<Daily>
     * @author lyj
     * @since 2015-5-6
     */
    public Page<Daily> getAllDailies(final long groupId, final int pageNum, final int pageSize, final int tag, final User userInfo) {

        //验证角色
        checkRole();

        //判断登录用户是否可以获取该专业群组信息
        if (!specialtyGroupService.getSpecialtyIds(userInfo).contains(groupId)) {
            throw new ServiceException("权限错误！");
        }

        Page<Daily> page = dailyDao.getAllDailies(groupId, pageNum, pageSize, tag);
        if (page.getItems().size() == 0) {
            log.debug("page.getItems().size() == 0");
            return new Page<>();
        }

        //循环绑定回复量
        log.debug("循环绑定回复量");
        for (Daily daily : page.getItems()) {
            daily.setReplyCount(dailyComCountDao.getCount(daily.getId(), dailyComCountDao.DAILY_COMMENT_COUNT).intValue());
        }

        log.debug("教学日志列表");
        return page;
    }


    /**
     * 跟据ID获取日志明细
     *
     * @param id 日志ID
     * @return Daily
     * @author lyj
     * @since 2015-5-6
     */
    public Daily getDetailById(final long id) {
        //验证角色
        checkRole();

        Daily daily = dailyDao.getDetailById(id);

        if (daily == null) {
            log.debug("daily == null");

            log.warn("获取日志明细失败：id->{}", id);
            throw new ServiceException("获取日志明细失败！");
        }

        log.debug("跟据ID获取日志明细");
        return daily;
    }
    //</editor-fold>

}
